﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;

namespace Utils.AppHelper
{
    public static class AppHelper
    {
        public static string GetJsonValue(string value)
        {
            return new ConfigurationBuilder().AddJsonFile("appsettings.json").Build()[value];
        }

        public static string GetConnection(string str)
        {
            return new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString(str);
        }

        /// <summary>
        /// 获取客户Ip
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetClientUserIp()
        {
            HttpContextAccessor http = new HttpContextAccessor();
            string ip = http.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(ip) && IsIP(ip))
            {
                return ip;
            }
            return "127.0.0.1";
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }


    }
}
